from xiaoyiwy.xiaoyi.config import *
import base64
import time
import json
import re

db = mysql()

# def img_base64(image):
#     with open(image, "rb") as fb:
#         img = fb.read()
#         base64_bytes = base64.b64encode(img)
#         base64_str = base64_bytes.decode("utf-8")
#         return base64_str


def ajax_test_add(mdpath):
        try:
            f_name = open(mdpath, 'r', encoding='UTF-8').read()
            # 成功获取到md文件内容啦
            return f_name
            #return {'content':f_name,'resCode':2000}
        except OSError as reason:
            return json.dumps({'err': str(reason),'resCode':5000})

# 首页默认展示最新两条数据
def article_get():
    conn = db.connection()
    cursor = conn.cursor()
    sql = "select id,title,img,label,release_time from drug_article ORDER BY release_time desc LIMIT 2"
    cursor.execute(sql)
    conn.commit()
    sqldata = cursor.fetchall()
    sqltitle = sql_index(cursor)
    resdata = []
    for sqlvalue in sqldata:  # 循环重构每一条sql返回数据字典
        data = {}
        # index为字段列表的下标，value为字段列表的值
        for index, value in enumerate(sqltitle):
            # data[title]为{}的key，sqlvalue[index]为{}的value--{"data[title]":"sqlvalue[index]"}
            data[value] = sqlvalue[index]
            if value == 'img':
                path = "http:xiaoyiwy:8080/images/"
                data[value] = path+data[value]
        resdata.append(data)  # 把{"data[title]":"sqlvalue[index]"}添加到resdata = []列表
    article_data = {
        "code": 1,
        "error": "",
        "data": resdata
    }
    mysql_close(cursor,conn)
    return article_data

# 文章详情添加热搜
def article_post(data):
    article_name = data['article_name']
    article_name = re.sub('\W+', '', article_name).replace("_", ' ')
    article_id = data['article_id']
    if article_id:
        if article_name:
            conn = db.connection()
            cursor = conn.cursor()
            sql = "select id,title,author,release_time,source,content from drug_article where id = '%s'" % article_id
            cursor.execute(sql)
            conn.commit()
            sqldata = cursor.fetchall()
            sqltitle = sql_index(cursor)
            resdata = []
            for sqlvalue in sqldata:  # 循环重构每一条sql返回数据字典
                resdatai = {}
                # index为字段列表的下标，value为字段列表的值
                for index, value in enumerate(sqltitle):
                    # data[title]为{}的key，sqlvalue[index]为{}的value--{"data[title]":"sqlvalue[index]"}
                    resdatai[value] = sqlvalue[index]
                    if value == 'content':
                        content = ajax_test_add(sqlvalue[index])
                        resdatai[value] = content
                resdata.append(resdatai)  # 把{"data[title]":"sqlvalue[index]"}添加到resdata = []列表
            article_data = {
                "code": 1,
                "error": "",
                "data": resdata
            }
            # 添加热搜
            now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            count_sql = "select count(id) from hot_article where article_id = '%s'" % (article_id)
            insert_sql = "insert into hot_article (article_id,title) value ('%s','%s')" % (article_id, article_name)
            updata_sql = "UPDATE hot_article SET update_time = '%s',frequency = frequency+1  WHERE article_id = '%s'" % (
            now, article_id)
            cursor.execute(count_sql)
            conn.commit()
            count_data = cursor.fetchall()
            try:
                if count_data[0][0] > 0:
                    cursor.execute(updata_sql)
                    conn.commit()
                else:
                    cursor.execute(insert_sql)
                    conn.commit()
            except:
                conn.rollback()
            mysql_close(cursor, conn)
            return article_data
        else:
            return {"error": "article_name为空"}
    else:
        return article_list(article_name)



# 文章列表
def article_list(article_name):
    conn = db.connection()
    cursor = conn.cursor()
    sql = "select id,title,release_time,label,source,content from drug_article order by create_time desc LIMIT 100"
    if len(article_name) > 0:
        sql = "select id,title,release_time,label,source,content from drug_article " \
              "where title like '%%%s%%' order by release_time desc" % article_name
    cursor.execute(sql)
    conn.commit()
    sqldata = cursor.fetchall()
    sqltitle = sql_index(cursor)
    resdata = []
    for sqlvalue in sqldata:  # 循环重构每一条sql返回数据字典
        resdatai = {}
        # index为字段列表的下标，value为字段列表的值
        for index, value in enumerate(sqltitle):
            # data[title]为{}的key，sqlvalue[index]为{}的value--{"data[title]":"sqlvalue[index]"}
            resdatai[value] = sqlvalue[index]
            if value == 'content':
                content = ajax_test_add(sqlvalue[index])
                resdatai[value] = content
        resdata.append(resdatai)  # 把{"data[title]":"sqlvalue[index]"}添加到resdata = []列表
    article_data = {
        "code": 1,
        "error": "",
        "data": resdata
    }
    mysql_close(cursor,conn)
    return article_data

# 热搜
def article_hot_get():
    conn = db.connection()
    cursor = conn.cursor()
    sql = "select article_id,title,frequency from hot_article order by frequency desc LIMIT 7"
    cursor.execute(sql)
    conn.commit()
    sqldata = cursor.fetchall()
    sqltitle = sql_index(cursor)
    resdata = []
    for sqlvalue in sqldata:  # 循环重构每一条sql返回数据字典
        data = {}
        # index为字段列表的下标，value为字段列表的值
        for index, value in enumerate(sqltitle):
            # data[title]为{}的key，sqlvalue[index]为{}的value--{"data[title]":"sqlvalue[index]"}
            data[value] = sqlvalue[index]
        resdata.append(data)  # 把{"data[title]":"sqlvalue[index]"}添加到resdata = []列表
    article_data = {
        "code": 1,
        "error": "",
        "data": resdata
    }
    return article_data
